package com.keqing.tomato.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.keqing.tomato.R;

import java.util.List;

public class RadioListAdapter<T> extends RecyclerView.Adapter<RadioListAdapter.ViewHolder> {
    private final List<T> data;
    private int mSelectedItem  = -1;
    private final OnItemClickListener mListener;


    public RadioListAdapter(List<T> data, int currentPos, OnItemClickListener listener) {
        this.data = data;
        this.mListener = listener;
        mSelectedItem = currentPos;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        View itemView;
        public TextView item;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            this.itemView = itemView;
            item = itemView.findViewById(R.id.item);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio_layout,
                parent, false);
        final ViewHolder holder = new ViewHolder(view);
        holder.item.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View v) {
                mSelectedItem = holder.getAdapterPosition();
                mListener.onClick(mSelectedItem);
                notifyDataSetChanged();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.item.setText(data.get(position).toString());
        holder.item.setEnabled(mSelectedItem != position);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public interface OnItemClickListener{
        void onClick(int pos);
    }

}
